package com.example.wecompose

import android.app.Activity
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.view.WindowCompat
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.toRoute
import com.example.wecompose.ui.ChatDetails
import com.example.wecompose.ui.ChatDetailsPage
import com.example.wecompose.ui.ChatList
import com.example.wecompose.ui.HomePage
import com.example.wecompose.ui.WeNavigationBar
import com.example.wecompose.ui.theme.WeComposeTheme
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    val viewModel: WeViewModel by viewModels()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false) // 关键配置

        val insetsController = WindowCompat.getInsetsController(window, window.decorView)

        lifecycleScope.launch {
            viewModel.isLightThemeFlow.collect {
                insetsController.isAppearanceLightStatusBars = it
            }
        }

        setContent {
            AppContent(viewModel)
        }
    }


}

@Composable
private fun AppContent(viewModel: WeViewModel) {
    WeComposeTheme(viewModel.theme) {
        SystemUiControlFix()

        // 创建导航控制器
        val navController = rememberNavController()

        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(WeComposeTheme.colors.background)
                .statusBarsPadding()
        ) {

            // NavHost 是导航的容器，负责管理页面之间的跳转和状态
            // 参数1：navController - 导航控制器，用于控制页面跳转、返回等操作
            // 参数2：HomePage - 起始路由（默认显示的首页）
            NavHost(
                navController, HomePage
            ) {
                // 定义"首页"路由对应的页面（使用类型安全导航，泛型<HomePage>指定路由类型）
                composable<HomePage> {
                    // 渲染首页组件 HomePage，并传入 viewModel 和导航回调
                    HomePage(viewModel) {
                        // 当首页触发导航到聊天详情页时，调用导航控制器的 navigate 方法
                        // ChatDetails(it.friend.id) 是目标路由，携带 userId 作为参数
                        navController.navigate(ChatDetails(it.friend.id))
                    }
                }
                // 定义"聊天详情页"路由对应的页面（同样使用类型安全导航）
                composable<ChatDetails>(
                    // 进入动画：从右侧滑入（initialOffsetX = { it } 表示初始位置在屏幕右侧外）
                    enterTransition = { slideInHorizontally(initialOffsetX = { it }) },
                    // 退出动画：向左侧滑出（targetOffsetX = { it } 表示最终位置在屏幕左侧外）
                    exitTransition = { slideOutHorizontally(targetOffsetX = { it }) }) {
                    // 从路由中解析出 userId 参数（toRoute<ChatDetails>() 转换为具体路由对象）
                    // 渲染聊天详情页组件，并传入 viewModel 和解析出的 userId
                    ChatDetailsPage(viewModel, it.toRoute<ChatDetails>().userId)
                }
            }


        }


    }
}


@Composable
fun SystemUiControlFix() {
    val context = LocalContext.current
    val isDarkTheme = WeComposeTheme.colors.background.luminance() < 0.5f

    DisposableEffect(Unit) {
        val window = (context as Activity).window
        val controller = WindowCompat.getInsetsController(window, window.decorView)

        // 确保状态栏完全透明
        window.statusBarColor = Color.Transparent.toArgb()

        // 根据主题调整图标颜色
        controller.isAppearanceLightStatusBars = !isDarkTheme

        onDispose { }
    }
}


@Preview
@Composable
private fun ChatListPreview() {
    val viewModel: WeViewModel = viewModel()
    WeComposeTheme {
        Column {
            val pagerState = rememberPagerState { 4 }
            HorizontalPager(pagerState, Modifier.weight(1f)) { page ->
                when (page) {
                    0 -> ChatList(viewModel.chats, {

                    }, viewModel)

                    1 -> Box(Modifier.fillMaxSize())
                    2 -> Box(Modifier.fillMaxSize())
                    3 -> Box(Modifier.fillMaxSize())

                }
            }
            val scope = rememberCoroutineScope()
            WeNavigationBar(pagerState.currentPage) {
                scope.launch {
                    pagerState.animateScrollToPage(it)
                }
            }
        }

    }
}






